<template>
  <page>
    <view class="chat-content" :style="{paddingBottom: emojiShow||voiceShow||extendShow?'800rpx':''}" @click="onExtendClose">
      <view class="loading-content" v-show="chatList.length < total">
        <fui-loading type="row" :isFixed="false"></fui-loading>
      </view>
      <view class="chat-list" v-for="(item,index) in chatList"
            :id="'chat_'+item._id"
            :key="index">
        <view class="chat-date">
          <view class="date" v-if="index !== 0 && item.create_time - chatList[index - 1].create_time >= 90000">
            <text>{{ util.formatTime(item.create_time,'{y}-{m}-{d} {h}:{i}') }}</text>
          </view>
        </view>
        <!--        自己-->
        <view class="chat-right" v-if="item.isSend">
          <view class="send-fail">
            <view class="fail" @click="onAfreshSend(item,index)" v-if="item.isBlack === 1">
              <image src="/static/images/icon/fssb_icon.png"></image>
            </view>
          </view>
          <view class="content" @longpress="onLongContent(item,index)">
            <view class="content-operation" v-show="contentIndex === index">
              <view class="operation-item">
                <view class="item" @click.stop="onCopy(item.content)" v-if="item.msgType === 'text'">
                  <image src="/static/images/icon/fzt_icon.png"></image>
                  <text>复制</text>
                </view>
                <view class="item" @click="onDelContent(item,index)">
                  <image src="/static/images/icon/sct_icon.png"></image>
                  <text>删除</text>
                </view>
              </view>
            </view>
            <view class="content-text" v-if="item.msgType === 'text' && !item.contentEmoji">
              <text>{{item.content}}</text>
              <text class="tag"></text>
            </view>
            <view class="content-text" v-else-if="item.msgType === 'text' && item.contentEmoji">
              <view class="text-img" v-for="value in item.contentEmoji">
                <image :src="'/static/images/emoji/'+value+'.png'" v-if="emojiItems.includes(value)"></image>
                <text v-else>{{value}}</text>
              </view>
              <text class="tag"></text>
            </view>
            <view class="content-image" @click.stop="onPreviewImage(item,index)" v-else-if="item.msgType === 'image'">
              <view class="image-item">
                <image :src="item.picUrl" model="widthFix" v-if="item.http"></image>
                <image :src="http + item.picUrl" model="widthFix" v-else></image>
              </view>
              <view class="loading" v-if="item.isLoading">
                <view class="load">
                  <fui-icon name="loading" color="#ffffff"></fui-icon>
                </view>
              </view>
            </view>
            <view class="content-voice" @click.stop="onVoicePlay(item,index)" v-else-if="item.msgType === 'voice'">
              <view class="time">
                <text>{{item.duration / 1000}}"</text>
              </view>
              <view class="icon">
                <image src="/static/images/icon/tyydx_right.gif" v-show="item.isVoicePay"></image>
                <image src="/static/images/icon/yyb_zi.png" v-show="!item.isVoicePay"></image>
              </view>
              <view class="tag"></view>
            </view>
            <view class="content-red" @click.stop="onRedPacket(item,index)" v-else-if="item.msgType === 'redPacket'">
              <view class="triangle"></view>
              <view class="packet-info">
                <view class="icon">
                  <image src="/static/images/icon/red_on_icon.png" v-if="item.isGet"></image>
                  <image src="/static/images/icon/red_off_icon.png" v-else></image>
                </view>
                <view class="title">
                  <text>{{item.content}}</text>
                </view>
              </view>
              <view class="desc-info">
                <view class="desc">
                  <text>红包消息</text>
                </view>
              </view>
            </view>
          </view>
          <view class="pic">
            <fui-avatar :src="userInfo.avatar_pic" width="80" height="80" shape="square"></fui-avatar>
          </view>
        </view>
        <!--        对方-->
        <view class="chat-left" v-else>
          <view class="pic" @click="onAvatar(item)">
            <fui-avatar :src="toUserInfo.avatar_pic" width="80" height="80" shape="square"></fui-avatar>
          </view>
          <view class="content" @longpress="onLongContent(item,index)">
            <view class="content-operation" v-show="contentIndex === index">
              <view class="operation-item">
                <view class="item" @click.stop="onCopy(item.content)" v-if="item.msgType === 'text'">
                  <image src="/static/images/icon/fzt_icon.png"></image>
                  <text>复制</text>
                </view>
                <view class="item" @click="onDelContent(item,index)">
                  <image src="/static/images/icon/sct_icon.png"></image>
                  <text>删除</text>
                </view>
              </view>
            </view>
            <view class="content-text" v-if="item.msgType === 'text' && !item.contentEmoji">
              <text>{{ item.content }}</text>
              <text class="tag"></text>
            </view>
            <view class="content-text" v-else-if="item.msgType === 'text' && item.contentEmoji">
              <view class="text-img" v-for="value in item.contentEmoji">
                <image :src="'/static/images/emoji/'+value+'.png'" v-if="emojiItems.includes(value)"></image>
                <text v-else>{{value}}</text>
              </view>
              <text class="tag"></text>
            </view>
            <view class="content-image" @click.stop="onPreviewImage(item,index)"  v-else-if="item.msgType === 'image'">
              <view class="image-item">
                <image :src="item.picUrl" model="widthFix" v-if="item.http"></image>
                <image :src="http + item.picUrl" model="widthFix" v-else></image>
              </view>
              <view class="loading" v-if="item.isLoading">
                <view class="load">
                  <fui-icon name="loading" color="#ffffff"></fui-icon>
                </view>
              </view>
            </view>
            <view class="content-voice" @click.stop="onVoicePlay(item,index)" v-else-if="item.msgType === 'voice'">
              <view class="icon">
                <image src="/static/images/icon/tyydx_left.gif" v-show="item.isVoicePay"></image>
                <image src="/static/images/icon/yyb_df.png" v-show="!item.isVoicePay"></image>
              </view>
              <view class="time">
                <text>{{item.duration / 1000}}"</text>
              </view>
              <view class="tag"></view>
            </view>
            <view class="content-red" @click.stop="onRedPacket(item,index)" v-else-if="item.msgType === 'redPacket'">
              <view class="triangle"></view>
              <view class="packet-info">
                <view class="icon">
                  <image src="/static/images/icon/red_on_icon.png" v-if="item.isGet"></image>
                  <image src="/static/images/icon/red_off_icon.png" v-else></image>
                </view>
                <view class="title">
                  <text>{{item.content}}</text>
                </view>
              </view>
              <view class="desc-info">
                <view class="desc">
                  <text>红包消息</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!--    聊天输入-->
    <view class="chat-input">
      <view class="input-info">
        <view class="voice" @click="onExtendVoice">
          <image src="/static/images/icon/yilt_icon.png"></image>
        </view>
        <view class="input-text">
          <input type="text" v-model="chatContent"
                 :placeholder="placeholder"
                 :focus="contentFocus"
                 @blur="contentBlur"
                 @input="inEditor">
        </view>
        <view class="extend">
          <view class="icon" @click="onExtendEmoji">
            <image src="/static/images/icon/jps_icon.png" v-show="emojiShow"></image>
            <image src="/static/images/icon/bqlt_icon.png" v-show="!emojiShow"></image>
          </view>
          <view class="icon" @click="onExtendAdd" :style="{display: chatContent?'none':'flex'}">
            <image src="/static/images/icon/kzxx_icon.png"></image>
          </view>
          <view class="send-btn" @click="sendData" :style="{display: chatContent?'flex':'none'}">
            <text>发送</text>
          </view>
        </view>
      </view>
      <!--      表情-->
      <view class="emoji-info" v-show="emojiShow">
        <view class="emoji-tab">
          <view class="tab active">
            <image src="/static/images/icon/bqlt_icon.png"></image>
          </view>
        </view>
        <view class="emoji-list">
          <view class="list" v-for="(item,index) in emojiItems"
                @click="onEmoji(item)"
                :key="index">
            <image :src="'/static/images/emoji/' + item + '.png'"></image>
          </view>
        </view>
      </view>
      <!--      扩展-->
      <view class="extend-info" v-show="extendShow">
        <view class="extend-item">
          <view class="item" @click="onExtendImg">
            <view class="icon">
              <image src="/static/images/icon/tpxz_icon.png"></image>
            </view>
            <text>图片</text>
          </view>
          <view class="item" @click="onExtendRedPacket">
            <view class="icon">
              <image src="/static/images/icon/hbxz_icon.png"></image>
            </view>
            <text>红包</text>
          </view>
        </view>
      </view>
      <!--      语音-->
      <view class="voice-info" v-show="voiceShow">
        <view class="voice-content">
          <view class="voice-sec">
            <view class="sec">
              <text>{{voiceSec}}S</text>
            </view>
          </view>
          <view class="voice-btn">
            <view class="btn" @click="onVoiceBtn(1)" v-if="voiceStatus === 0">
              <view class="btn-bg"></view>
              <view class="btn-start"></view>
            </view>
            <view class="btn" @click="onVoiceBtn(2)" v-else-if="voiceStatus === 1">
              <view class="btn-bg btn-an"></view>
              <view class="btn-am">
                <view class="rot"></view>
              </view>
            </view>
            <view class="btn-finish" v-else-if="voiceStatus === 2">
              <view class="del" @click="onRecordDel">
                <image src="/static/images/icon/scljt_icon.png"></image>
              </view>
              <view class="btn-wc" @click="onRecordPlay">
                <image src="/static/images/icon/yinbf_iocn.png"></image>
              </view>
              <view class="send" @click="onRecordSend">
                <image src="/static/images/icon/dh_icon.png"></image>
              </view>
            </view>
          </view>
          <view class="voice-hint">
            <text v-if="voiceStatus === 0 &&!isRecordPlay">点击录音</text>
            <text v-else-if="voiceStatus === 1 && !isRecordPlay">录音中</text>
            <text v-else-if="voiceStatus === 2 && !isRecordPlay">点击播放</text>
            <text v-if="isRecordPlay">正在播放</text>
          </view>
        </view>
      </view>
    </view>
<!--    红包-->
    <red-packet-poup ref="RedPacketPopup" @getConfirm="getRedPacketConfirm"></red-packet-poup>
  </page>
</template>

<script setup>
import {onLoad, onHide, onPageScroll, onUnload, onShow} from "@dcloudio/uni-app";
import {getCurrentInstance, nextTick, onMounted, ref, watch} from 'vue'
import {useStore} from 'vuex'
import {chatRecordList, deleteChatMessage, FileUpload, findSid, getUserInfo} from "../../api/api";
import chat from '../../common/chat';
import util from '../../common/util';
import emoji from '../../common/emoji';
import RedPacketPoup from "./components/RedPacketPoup/RedPacketPoup.vue";
import {checkRedPacket} from "../../api/wallet";

const {proxy} = getCurrentInstance();
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
const store = useStore();
const RedPacketPopup = ref(null);

const http = process.env.config[process.env.NODE_ENV].baseURL
const placeholder = ref('');
// 聊天内容
const chatContent = ref('');
// 聊天光标位置
const inputCursor = ref(0);
// 表情列表
const emojiItems = emoji;
// 表情显示
const emojiShow = ref(false);
// 扩展显示
const extendShow = ref(false);
// 语音显示
const voiceShow = ref(false);
const voiceSec = ref(0);
// 语音状态 0 未开始 1 开始录音 2 录音结束
const voiceStatus = ref(0);
// 录音是否播放
const isRecordPlay = ref(false);
const voiceUrl = ref('');
// 音频播放索引
const voiceIndex = ref(0);
let voiceTimer = null;
// 数据
const to_user_id = ref('');
const to_sid = ref('');
const user_id = proxy.$global.user_id;
const userInfo = proxy.$global.userInfo;
const toUserInfo = proxy.$global.toUserInfo;
// 聊天记录
const chatList = ref([]);
// 滑动
const scrollTop = ref(0);
const contentFocus = ref(false);
const chatId = ref('');
// 长按消息
const contentIndex = ref(-1);
// 分页
let pageNo = 1;
let total = 0;

onLoad((params) => {
  uni.setNavigationBarTitle({
    title: proxy.$global.toUserInfo.nickname,
  })
  to_user_id.value = params.to_user_id || '';
  // 红包消息
  uni.$on('redPacketData',function(data){
    console.log(data);
    setRedPacket(data);
  })
  getData();
  getSidData();
  sendRead();
  recordListener();
  voiceListener();
})

onShow(() =>{

})
onHide(() =>{
  innerAudioContext.pause();
  innerAudioContext.stop();
})
onUnload(() =>{
  uni.$off('redPacketData');
  innerAudioContext.stop();
  innerAudioContext.pause();
})
onPageScroll((e) =>{
  scrollTop.value = e.scrollTop;
  if(e.scrollTop <= 0 && chatList.value.length < total){
    chatId.value = `chat_${chatList.value[0]._id}`;
    pageNo++;
    getData();
  }
})

/**
 * 发送已读消息
 */
function sendRead(){
  chat.send('readMessage',{
    to_user_id: to_user_id.value,
    user_id: user_id
  });
}
/**
 * 获取sid
 */
function getSidData() {
  findSid({
    to_user_id: to_user_id.value
  }).then(res => {
    to_sid.value = res.sid;
  })
}
/**
 * 获取聊天记录
 */

function getData() {
  chatRecordList({
    limit: 20,
    page: pageNo,
    to_user_id: to_user_id.value
  }).then(res => {
    for (let i = 0; i < res.data.data.length; i++) {
      res.data.data[i].contentEmoji = util.emojiMatch(res.data.data[i].content);
    }
    if (pageNo === 1) {
      chatList.value = res.data.data;
      total = res.data.total;
      scrollAm();
    }else {
      chatList.value = [...res.data.data,...chatList.value];
      nextTick(() =>{
        scrollFixed();
      })
    }
  })
}
/**
 * 扩展表情点击
 */
function onExtendEmoji(){
  emojiShow.value = !emojiShow.value;
  contentFocus.value = emojiShow.value !== true;
  extendShow.value = false;
  voiceShow.value = false;
  scrollAm();
}
/**
 * 扩展加号点击
 */
function onExtendAdd(){
  extendShow.value = !extendShow.value;
  emojiShow.value = false;
  voiceShow.value = false;
  scrollAm();
}
/**
 * 扩展语音点击
 */
function onExtendVoice(){
  voiceShow.value = !voiceShow.value;
  extendShow.value = false;
  emojiShow.value = false;
  scrollAm();
}

/**
 * 扩展关闭点击
 */
function onExtendClose(){
  voiceShow.value = false;
  extendShow.value = false;
  emojiShow.value = false;
  closeContentPopup();
  scrollAm();
}
/**
 * 初始化文本输入
 */
// function onEditorReady() {
//   // #ifdef APP-PLUS || H5 ||MP-WEIXIN
//   uni.createSelectorQuery().select('#editor').context((res) => {
//     editorCtx = res.context;
//     // console.log(editorCtx);
//     // chatContent.value = '娃哈哈<img src="/static/images/icon/bqlt_icon.png" height="20" width="20">sdasd'
//     // editorCtx.setContents({
//     //   html: chatContent.value
//     // })
//     // setTimeout(() =>{
//     //   chatContent.value += '<img src="/static/images/icon/bqlt_icon.png" height="20" width="20">';
//     //   editorCtx.setContents({
//     //     html: chatContent.value
//     //   })
//     // },2000)
//   }).exec()
//   // #endif
// }
/**
 * 内容输入
 * @param e
 */
function inEditor (e) {
  inputCursor.value = e.detail.cursor;
}
/**
 * 内容失去焦点
 */
function contentBlur(e){
  inputCursor.value = e.detail.cursor;
}
/**
 * 发送消息
 */
function sendData(data = {}){
  const info = {
    sid: to_sid.value,   // 需要发送的socketid
    user_id: proxy.$global.user_id,   // 自己的用户id
    to_user_id: to_user_id.value,   // 对方的用户id
    msgType: data.msgType||'text',              // 消息类型 text 文本 image 图片 voice 语音
    content: chatContent.value||data.content,    // 文本消息内容
    contentEmoji: util.emojiMatch(chatContent.value),
    picUrl: data.picUrl||'',                   // 图片地址
    voiceUrl: data.voiceUrl||'',                 // 语音地址
    duration: data.duration||0,                  // 时长（目前是语音时长毫秒级）
    isLoading: data.isLoading||false,  // 消息状态
    isVoicePay: data.isVoicePay||false,                  // 语音播放状态
    extend_id: data.extend_id||'',            // 扩展id
    isSend: 1,            // 发送人
    http: data.http||'',  // 图片地址（存在是本地）
    create_time: new Date().getTime(),  // 发送消息时间
    index: chatList.value.length,
  }
  chatList.value.push(info)
  // 发送消息
  if(info.msgType === 'text'){
    sendSubmit(info);
  }else if(info.msgType === 'redPacket'){
    sendSubmit(info);
  }
  // 清空已发送消息
  chatContent.value = '';
  // 滑动底部
  scrollAm();
}
/**
 * 发送给服务器
 */
function sendSubmit(data){
  const info = {
    sid: to_sid.value,   // 需要发送的socketid
    user_id: proxy.$global.user_id,   // 自己的用户id
    to_user_id: to_user_id.value,   // 对方的用户id
    msgType: data.msgType||'text',              // 消息类型 text 文本 image 图片 voice 语音
    content: data.content,    // 文本消息内容
    picUrl: data.picUrl||'',                   // 图片地址
    voiceUrl: data.voiceUrl||'',                 // 语音地址
    duration: data.duration||0,                  // 时长（目前是语音时长毫秒级）
    extend_id: data.extend_id||'',                  // 扩展id字段
    index: data.index,
  }
  chat.send('chatSend',info);
  if(data.index !== -1){
    chatList.value[data.index].isLoading = false;
  }
}
/**
 * 收到消息
 */
function putMessage(data = {}){
  console.log(data);
  chatList.value.push({
    _id: data._id,
    to_user_id: data.to_user_id,
    user_id: data.user_id,
    content: data.content,
    contentEmoji: util.emojiMatch(data.content),
    create_time: data.create_time,
    duration: data.duration||0,
    extend_id: data.extend_id||'',
    msgType: data.msgType||'text',
    picUrl: data.picUrl||'',
    voiceUrl: data.voiceUrl||'',
  })
  scrollAm();
  // 循环查找对应列表删除未读消息
  for (let i = 0; i < store.state.chat.chatList.length;i++) {
    if(store.state.chat.chatList[i].user_id === data.user_id){
      store.state.chat.chatList.splice(i,1);
      i = i - 1;
    }
  }
  store.commit('setCountMsg',store.state.chat.countMsg - 1);
  sendRead();
}
/**
 * 滑动动画设置
 */
function scrollAm() {
  nextTick(() =>{
    uni.pageScrollTo({
      scrollTop: 9999999,
      duration: 0
    });
  })
}
/**
 * 固定滑动位置
 */
function scrollFixed() {
  const query = uni.createSelectorQuery().in(proxy);
  query.select(`#${chatId.value}`).boundingClientRect(data => {
    uni.pageScrollTo({
      scrollTop: data.top,
      duration: 0
    });
  }).exec();
}
/**
 * 表情点击
 * @param item
 */
function onEmoji(item){
  // 在最后
  if(inputCursor.value === chatContent.value.length){
    chatContent.value += `[${item}]`;
    inputCursor.value = chatContent.value.length;
    return;
  }
  chatContent.value = insertStr(chatContent.value,inputCursor.value,`[${item}]`);
}

/**
 * 插入字符串
 * @param source
 * @param start
 * @param newStr
 * @returns {*}
 */
function insertStr(source, start, newStr) {
  return source.slice(0, start) + newStr + source.slice(start)
}


/**
 * 扩展图片点击
 */
function onExtendImg(){
  let sourceType = ['album'];
  uni.chooseImage({
    count: 9, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: sourceType,
    success: (res) => {
      console.log(res);
      extendShow.value = false;
      let tempFilePaths = res.tempFilePaths;
      for (let i = 0; i < tempFilePaths.length; i++) {
        sendData({
          msgType: 'image',
          content: tempFilePaths[i],
          picUrl: tempFilePaths[i],
          http: tempFilePaths[i],
          isLoading: true,
        });
        let index = chatList.value.length - 1;
        upLoadFile(tempFilePaths[i], index,{
          msgType: 'image',
        });
      }
    }
  });
}

/**
 * 上传图片
 * @param file
 * @param index
 * @param item
 */
function upLoadFile(file, index,item = {}){
  FileUpload(file,{
    url: 'chat'
  }).then(res =>{
    sendSubmit({
      msgType: item.msgType,
      content: res.data.url,
      picUrl: item.msgType === 'image' ? res.data.url : '',
      voiceUrl: item.msgType === 'voice' ? res.data.url : '',
      duration: item.duration||0,
      isLoading: false,
      index: index,
    });
  })
}
/**
 * 查看图片
 * @param item
 * @param index
 */
function onPreviewImage(item, index) {
  let url = item.http ? `${item.picUrl}` : `${http}${item.picUrl}`;
  uni.previewImage({
    urls: [url],
    longPressActions: {}
  });
}

/**
 * 录音点击
 * @param status
 */
function onVoiceBtn(status){
  voiceStatus.value = status;
  if(status === 1){
    startRecord();
  }else if(status === 2){
    endRecord();
  }
}

/**
 * 开始录音
 */
function startRecord() {
  console.log('开始录音');
  recorderManager.start();
  // 录音时长定时器
  clearInterval(voiceTimer);
  voiceTimer = setInterval(() =>{
    voiceSec.value++;
  },1000)
}

/**
 * 结束录音
 */
function endRecord() {
  console.log('录音结束');
  recorderManager.stop();
  clearInterval(voiceTimer);
}

/**
 * 录音监听
 */
function recordListener(){
  recorderManager.onStop(function (res) {
    console.log('recorder stop' + JSON.stringify(res));
    voiceUrl.value = res.tempFilePath;
  });
}

/**
 * 录音播放点击
 */
function onRecordPlay(){
  if(isRecordPlay.value){
    return;
  }
  let duration = voiceSec.value;
  let timer = null;
  innerAudioContext.src = voiceUrl.value;
  innerAudioContext.play();
  isRecordPlay.value = true;
  // 播放定时器
  clearInterval(timer);
  timer = setInterval(() =>{
    voiceSec.value--;
    if(voiceSec.value <= 0){
      clearInterval(timer);
      voiceSec.value = duration;
      isRecordPlay.value = false;
    }
  },1000)
}

/**
 * 录音删除
 */
function onRecordDel(){
  const fileSystemManager = wx.getFileSystemManager();
  fileSystemManager.removeSavedFile({
    filePath: voiceUrl.value,
    success: res => {
      console.log(res,'删除成功');
    },
    fail: err =>{
      console.log(err,'删除失败');
    }
  })
  voiceUrl.value = '';
  voiceSec.value = 0;
  voiceStatus.value = 0;
}

/**
 * 录音发送
 */
function onRecordSend(){
  sendData({
    msgType: 'voice',
    content: voiceUrl.value,
    picUrl: '',
    voiceUrl: voiceUrl.value,
    duration: voiceSec.value * 1000,
    http: voiceUrl.value,
    isLoading: true,
  });
  let index = chatList.value.length - 1;
  upLoadFile(voiceUrl.value, index,{
    msgType: 'voice',
    duration: voiceSec.value * 1000
  });
  voiceShow.value = false;
  voiceUrl.value = '';
  voiceSec.value = 0;
  voiceStatus.value = 0;
}

/**
 * 播放语音
 * @param item
 * @param index
 */
function onVoicePlay(item,index){
  chatList.value[voiceIndex.value].isVoicePay = false;
  chatList.value[index].isVoicePay = true;
  voiceIndex.value = index;
  innerAudioContext.src = item.http ? item.voiceUrl : `${http}${item.voiceUrl}`;
  innerAudioContext.play();
}

/**
 * 音频监听
 */
function voiceListener(){
  innerAudioContext.onEnded(() => {
    chatList.value[voiceIndex.value].isVoicePay = false;
    console.log('自然播放结束');
  });
  innerAudioContext.onStop(() => {
    chatList.value[voiceIndex.value].isVoicePay = false;
    console.log('停止播放结束');
  });
}

/**
 * 重新发送
 * @param item
 * @param index
 */
function onAfreshSend(item,index){
  deleteChatMessage({
    _id: item._id,
  }).then(res =>{
    chatList.value.splice(index,1);
    item.isBlack = 0;
    item.create_time = new Date().getTime();
    item.index = chatList.value.length;
    chatList.value.push(item);
    sendSubmit(item);
  })
}

/**
 * 头像点击
 * @param item
 */
function onAvatar(item){
  console.log(item);
  uni.navigateTo({
    url: `/pages/FriendInfo/FriendInfo?to_user_id=${item.to_user_id}&isBack=1`
  })
}

/**
 * 长按内容
 * @param item
 * @param index
 */
function onLongContent(item,index){
  contentIndex.value = index;
}

/**
 * 关闭内容弹窗
 */
function closeContentPopup(){
  contentIndex.value = -1;
}
/**
 * 复制
 * @param text
 */
function onCopy(text){
  uni.setClipboardData({
    data: text,
    success: function () {
      closeContentPopup();
      proxy.$way.toast('复制成功');
    }
  });
}

/**
 * 消息删除
 * @param item
 * @param index
 */
function onDelContent(item,index){
  uni.showModal({
    title: '提示',
    content: '确认删除？',
    success: function (res) {
      if (!res.confirm) {
        return;
      }
      deleteChatMessage({
        _id: item._id,
      }).then(res =>{
        chatList.value.splice(index,1);
      })
    }
  });
}

/**
 * 发送红包扩展点击
 */
function onExtendRedPacket(){
  uni.navigateTo({
    url: `/pages/RedPacketSend/RedPacketSend?to_user_id=${to_user_id.value}`
  })
}

/**
 * 红包消息设置
 * @param data
 */
function setRedPacket(data){
  sendData({
    msgType: 'redPacket',
    content: data.greetings,
    extend_id: data.red_packet_id,
  });
}

/**
 * 红包消息点击
 * @param item
 * @param index
 */
function onRedPacket(item,index){
  checkRedPacket({
    red_packet_id: item.extend_id,
    _id: item._id,
  }).then(res =>{
    // 判断是否已领取
    if (res.data.check){
      chatList.value[index].isGet = 1;
    }
    // 判断是否是自己发起
    if(!item.isSend){
      item.nickname = toUserInfo.nickname;
      item.avatar_pic = toUserInfo.avatar_pic;
      item.check = res.data.check;
      item.isOneself = 0;
      RedPacketPopup.value?.open(item,index);
      return;
    }
    uni.navigateTo({
      url: `/pages/RedPacketResult/RedPacketResult?red_packet_id=${item.extend_id}`
    })
  })
}

/**
 * 红包领取确认回调
 * @param index
 */
function getRedPacketConfirm(index){
  chatList.value[index].isGet = 1;
  checkRedPacket({
    red_packet_id: chatList.value[index].extend_id,
    _id: chatList.value[index]._id,
  }).then(res =>{
    console.log('检查更新成功');
  })
}
watch(
    [()=> store.state.chat.chatData,()=> store.state.chat.chatBackData],
    (newValue,oldValue) => {
      const chatData = newValue[0];
      const chatBackData = newValue[1];
      // 发送的回执消息
      if(chatBackData.code){
        chatList.value[chatBackData.data.index]._id = chatBackData.data._id;
        // 消息发送失败
        if(chatBackData.code === 204){
          chatList.value[chatBackData.data.index].isBlack = 1;
        }
      }
      // 接收到消息
      if(chatData._id){
        putMessage(chatData);
      }
    },
    {deep: true}
)
</script>

<style lang="scss">
@import "ChatPage.scss";
</style>
